package pzl.mn.practice.retrofit;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import pzl.mn.practice.Config;
import pzl.mn.practice.R;
import pzl.mn.practice.retrofit.Bean.req.CodeLang;
import pzl.mn.practice.retrofit.Bean.resp.Singer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitActivity extends AppCompatActivity {
    String TAG = Config.TAG0 + "_Retrofit";
    TextView tvMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
        tvMsg = findViewById(R.id.tvMsg);
    }


    public void click(View view) {
        tvMsg.setText("");
        switch (view.getId()) {
            case R.id.btnRetrofitGet:
                get(view);
                break;
            case R.id.btnRetrofitGet2:
                get2(view);
                break;
            case R.id.btnRetrofitGet3:
                get3(view);
                break;
            case R.id.btnRetrofitPost:
                post(view);
                break;
        }
    }

    /**
     * post 异步
     *
     * @param view
     */
    private void post(final View view) {
        OkHttpClient okHttpClient = getLoggingOkHttpClint(new OkHttpClient.Builder()).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.178.121.17:8080/")
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        final ILocalService service = retrofit.create(ILocalService.class);
        CodeLang codeLang = CodeLang.getInstance();
        codeLang.id = 1;
        codeLang.name = "java";
        codeLang.time = System.currentTimeMillis();
        String body = new Gson().toJson(codeLang);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body);
        final Call<ResponseBody> call = service.reqPostParam1(requestBody);
        //post 异步
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String result = null;
                try {
                    result = response.body().string();
                    Log.i(TAG, result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                final String finalResult = result;
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        tvMsg.append(finalResult + '\n');
                    }
                });
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("连接失败 " + t.getMessage());
            }
        });
    }

    /**
     * get3 同步请求
     *
     * @param view
     */
    private void get3(final View view) {
        OkHttpClient okHttpClient = getLoggingOkHttpClint(new OkHttpClient.Builder()).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.178.121.17:8080/")
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        final ILocalService service = retrofit.create(ILocalService.class);
        final Call<Singer> call = service.reqGetParam1("json1");
        new Thread() {
            @Override
            public void run() {
                try {
                    Response<Singer> response = call.execute();//同步请求
                    final Singer result = response.body();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMsg.append(result.toString() + '\n');
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    /**
     * get2 异步请求 json结构
     *
     * @param view
     */
    private void get2(final View view) {
        OkHttpClient okHttpClient = getLoggingOkHttpClint(new OkHttpClient.Builder()).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.178.121.17:8080/")
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        final ILocalService service = retrofit.create(ILocalService.class);
        Call<Singer> call = service.reqGetParam1("json1");
        //异步请求
        call.enqueue(new Callback<Singer>() {
            //请求成功时回调
            @Override
            public void onResponse(Call<Singer> call, Response<Singer> response) {
                Singer result = null;
                try {
                    result = response.body();
                    Log.i(TAG, result.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                final Singer finalResult = result;
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        tvMsg.append(finalResult.toString() + '\n');
                    }
                });
            }

            @Override
            public void onFailure(Call call, Throwable throwable) {
                System.out.println("连接失败 " + throwable.getMessage());
            }
        });
    }


    /**
     * get 异步请求 原始串
     *
     * @param view
     */
    private void get(final View view) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .build();
        final IGitHubService service = retrofit.create(IGitHubService.class);
        //获取原始返回的json数据 ResponseBody
        Call<ResponseBody> reposCall = service.listRepos("ace2014");
        //异步请求
        reposCall.enqueue(new Callback<ResponseBody>() {
            //请求成功时回调
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String result = "";
                try {
                    result = response.body().string();
                    Log.i(TAG, result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                final String finalResult = result;
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        tvMsg.append(finalResult + '\n');
                    }
                });
            }

            @Override
            public void onFailure(Call call, Throwable throwable) {
                System.out.println("连接失败 " + throwable.getMessage());
            }
        });
    }


    /**
     * 日志拦截器
     *
     * @return
     */
    private OkHttpClient.Builder getLoggingOkHttpClint(OkHttpClient.Builder builder) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i(TAG, message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);
        return builder;
    }

}
